﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis
{
    /// <summary>
    /// 创建PDF文件，用于审核通过生成PDF
    /// </summary>
    /// 创建时间：2023-1-11 16:56:34。作者：王浩力
    internal static class MakePdfHelpter
    {
        /// <summary>
        /// 创建PDF文件
        /// </summary>
        /// <param name="pdfSavePath">pdf文件名，不包含.pdf</param>
        /// <param name="strTmplName">模板文件</param>
        /// <param name="data">数据源</param>
        ///  <param name="func">自定义处理文件保存的文件夹</param>
        /// 创建时间：2023-1-11 16:56:34。作者：王浩力
        public static void CheckPassLoadXps(string pdfSavePath, string strTmplName, object data, Func<string> func = null)
        {
            FlowDocument doc = (FlowDocument)Application.LoadComponent(new Uri("FlowDocumentPage\\" + strTmplName, UriKind.Relative));
            doc.PagePadding = new Thickness(40);
            doc.DataContext = data;

            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                /**   添加时间：2023-1-6 17:14:28。作者：王浩力
                如果文档中有图片，则鼠标悬浮在图片上之时触发异常：
                Entries cannot be opened multiple times in Update mode
                参考文档：
https://github.com/dotnet/runtime/issues/24962   
                
                IOException when viewing XpsDocument with DocumentViewer
https://github.com/dotnet/runtime/issues/39430

                DocumentViewer鼠标悬浮图片异常
                https://ask.csdn.net/questions/7502600
                 */

                MemoryStream ms = new MemoryStream();
                try
                {
                    //构造一个基于内存的xps document            
                    Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
                    Uri uri = new Uri($"pack://{DateTime.Now.Ticks}.xps");
                    PackageStore.AddPackage(uri, package);

                    XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.NotCompressed, uri.AbsoluteUri);

                    //将flow document写入基于内存的xps document中去
                    XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
                    writer.Write(((IDocumentPaginatorSource)doc).DocumentPaginator);

                    string pdfDir = MyConfigReader.GetConfigValue("proocessPassPdfFolderPath");
                    string pdfDirZDY = func?.Invoke();
                    if (!string.IsNullOrWhiteSpace(pdfDirZDY))
                    {
                        pdfDir = System.IO.Path.Combine(pdfDir, pdfDirZDY);
                    }  
                    if (!System.IO.Directory.Exists(pdfDir))
                    {
                        System.IO.Directory.CreateDirectory(pdfDir);
                    }

                    string pdfFileWork = System.IO.Path.Combine(pdfDir, pdfSavePath + ".pdf");
                    if (File.Exists(pdfFileWork))
                    {
                        File.Delete(pdfFileWork);
                    }

                    //保存xps文档为pdf文件
                    PdfSharp.Xps.XpsConverter.Convert(xpsDocument, pdfFileWork, 0);

                    //关闭基于内存的xps document
                    xpsDocument.Close();

                    //package.Flush();
                    //package.Close();
                }
                catch (Exception ex)
                {
                    LogHelpter.AddLog("创建流文档异常2", null, "WindowProofreadPrintPreview.LoadXps，异常：" + ex.Message);
                }
                finally
                {
                    ms?.Close();
                    ms?.Dispose();
                }
            }, System.Windows.Threading.DispatcherPriority.Render);
        }

    }
}
